package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.*;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.service.ICheckInService;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 入住Service业务层处理
 * 
 * @author zzyl_mh
 * @date 2025-08-11
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return checkInMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return checkInMapper.deleteById(id);
    }

    /**
     * 入住详情
     * @param id
     * @return
     */
    @Override
    @Transactional
    public CheckInDetailVo detail(Long id) {
        //1.通过id查询入住信息
        CheckIn checkIn = checkInMapper.selectById(id);
        //2.封装checkInConfigVo对象
        CheckInConfigVo checkInConfigVo = getCheckInConfigVo(checkIn);
        //3.封装checkInElderVo对象
        CheckInElderVo checkInElderVo = getCheckInElderVo(checkIn);
        //4.封装contract对象
        Contract contract = getContract(checkIn);
        //5.封装elderFamilyVoList
        List<ElderFamilyVo> elderFamilyDtoList = getelderFamilyVoList(checkIn);
        //6.封装对象并返回
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        checkInDetailVo.setCheckInElderVo(checkInElderVo);
        checkInDetailVo.setContract(contract);
        checkInDetailVo.setElderFamilyVoList(elderFamilyDtoList);
        return checkInDetailVo;
    }

    /**
     * 获取elderFamilyVoList
     * @param checkIn
     * @return
     */
    private List<ElderFamilyVo> getelderFamilyVoList(CheckIn checkIn) {
        String remark = checkIn.getRemark();
        // 使用 JSON 工具类解析
        List<ElderFamilyDto> elderFamilyDtoList = StringUtils.isBlank(remark) ?
                new ArrayList<>() :
                JSON.parseArray(remark, ElderFamilyDto.class);
        List<ElderFamilyVo> elderFamilyVos = BeanUtil.copyToList(elderFamilyDtoList, ElderFamilyVo.class);
        return elderFamilyVos;
    }

    /**
     * 获取contract对象
     * @param checkIn
     * @return
     */
    private Contract getContract(CheckIn checkIn) {
        LambdaQueryWrapper<Contract> contractQuery = new LambdaQueryWrapper<>();
        contractQuery.eq(Contract::getElderId,checkIn.getElderId());
        Contract contract = contractMapper.selectOne(contractQuery);
        return contract;
    }

    /**
     * 获取checkInElderVo对象
     * @param checkIn
     * @return
     */
    private CheckInElderVo getCheckInElderVo(CheckIn checkIn) {
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        LambdaQueryWrapper<Elder> elderQuery = new LambdaQueryWrapper<>();
        elderQuery.eq(Elder::getId,checkIn.getElderId());
        Elder elder = elderMapper.selectOne(elderQuery);
        Integer age = calculateAge(elder.getBirthday());
        BeanUtil.copyProperties(elder,checkInElderVo);
        checkInElderVo.setAge(age);
        return checkInElderVo;
    }

    /**
     * 获取checkInConfigVo对象
     * @param checkIn
     * @return
     */
    private CheckInConfigVo getCheckInConfigVo(CheckIn checkIn) {
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        LambdaQueryWrapper<CheckInConfig> checkInConfigQuery = new LambdaQueryWrapper<>();
        checkInConfigQuery.eq(CheckInConfig::getCheckInId,checkIn.getId());
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(checkInConfigQuery);
        BeanUtil.copyProperties(checkInConfig,checkInConfigVo);
        checkInConfigVo.setBedNumber(checkIn.getBedNumber());
        return checkInConfigVo;
    }

    /**
     * 根据出生日期字符串计算年龄（精确到是否已过生日）
     * @param birthDateStr 格式必须为 "yyyy-MM-dd"
     * @return 年龄（整数），如果日期非法或未来日期返回 -1
     */
    public static Integer calculateAge(String birthDateStr) {
        try {
            LocalDate birthDate = LocalDate.parse(birthDateStr, DATE_FORMATTER);
            LocalDate currentDate = LocalDate.now();

            // 检查未来日期
            if (birthDate.isAfter(currentDate)) {
                return -1; // 或抛出自定义异常
            }

            // 计算年龄
            int age = Period.between(birthDate, currentDate).getYears();

            // 如果今年生日未过，年龄减1（更精确）
            if (currentDate.getMonthValue() < birthDate.getMonthValue() ||
                    (currentDate.getMonthValue() == birthDate.getMonthValue() &&
                            currentDate.getDayOfMonth() < birthDate.getDayOfMonth())) {
                age--;
            }

            return age;
        } catch (Exception e) {
            return -1; // 格式错误或解析失败
        }
    }

    @Override
    @Transactional
    public void apply(CheckInApplyDto checkInApplyDto) {
        //1.检验老人是否入住
        if(checkElderIsCheckIn(checkInApplyDto)){
            //1.1入住 -> 抛出异常(老人已入住)
            throw new BaseException("老人已入住");
        }
        //2.更新床位状态为已入住
        Bed bed = updateBedStatus(checkInApplyDto);
        //3.新增或更新老人
        Elder elder = insertOrUpdateElder(checkInApplyDto,bed);
        //4.新增签约办理
        insertConstract(elder,checkInApplyDto);
        //5.新增入住信息
        CheckIn checkIn = insertCheckIn(elder,checkInApplyDto);
        //6.新增入住配置
        insertCheckInConfig(checkIn, checkInApplyDto);
    }

    private void insertCheckInConfig(CheckIn checkIn, CheckInApplyDto checkInApplyDto) {
        CheckInConfig checkInConfig = new CheckInConfig();
        CheckInConfigDto checkInConfigDto = checkInApplyDto.getCheckInConfigDto();
        BeanUtil.copyProperties(checkInConfigDto,checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigMapper.insert(checkInConfig);
    }

    /**
     * 新增入住信息
     * @param elder
     * @param checkInApplyDto
     */
    private CheckIn insertCheckIn(Elder elder, CheckInApplyDto checkInApplyDto) {
        CheckIn checkIn = new CheckIn();
        CheckInConfigDto checkInConfigDto = checkInApplyDto.getCheckInConfigDto();
        List<ElderFamilyDto> elderFamilyDtoList = checkInApplyDto.getElderFamilyDtoList();
        BeanUtil.copyProperties(elder,checkIn,"id");
        checkIn.setElderName(elder.getName());
        checkIn.setElderId(elder.getId());
        checkIn.setStartDate(checkInConfigDto.getStartDate());
        checkIn.setEndDate(checkInConfigDto.getEndDate());
        checkIn.setNursingLevelName(checkInConfigDto.getNursingLevelName());
        checkIn.setStatus(0);
        checkIn.setRemark(JSONUtil.toJsonStr(elderFamilyDtoList));
        checkInMapper.insert(checkIn);
        return checkIn;
    }

    /**
     * 插入合同信息
     * @param elder
     * @param checkInApplyDto
     */
    private void insertConstract(Elder elder, CheckInApplyDto checkInApplyDto) {
        Contract contract = new Contract();
        CheckInContractDto checkInContractDto = checkInApplyDto.getCheckInContractDto();
        CheckInConfigDto checkInConfigDto = checkInApplyDto.getCheckInConfigDto();
        BeanUtil.copyProperties(checkInContractDto,contract);
        contract.setElderId(elder.getId().intValue());
        contract.setContractNumber("HT" + CodeGenerator.generateContractNumber());
        contract.setElderName(elder.getName());
        contract.setStartDate(checkInConfigDto.getStartDate());
        contract.setEndDate(checkInConfigDto.getEndDate());
        contract.setStatus(0);
        contractMapper.insert(contract);
    }

    /**
     * 新增或者插入老人信息
     * @param checkInApplyDto
     * @param bed
     * @return
     */
    private Elder insertOrUpdateElder(CheckInApplyDto checkInApplyDto, Bed bed) {
        //1.准备老人数据
        Elder elder = new Elder();
        CheckInElderDto checkInElderDto = checkInApplyDto.getCheckInElderDto();
        BeanUtil.copyProperties(checkInElderDto,elder);
        elder.setBedId(bed.getId());
        elder.setBedNumber(bed.getBedNumber());
        elder.setStatus(1);
        //准备判断条件
        LambdaQueryWrapper<Elder> elderWrapper = new LambdaQueryWrapper<>();
        //前面业务逻辑判断过老人状态,此处无需判断
        elderWrapper.eq(Elder::getIdCardNo,elder.getIdCardNo());
        Elder DbElder = elderMapper.selectOne(elderWrapper);
        if(ObjUtil.isNull(DbElder)){
            //没有这个老人,插入
            elderMapper.insert(elder);
        }else {
            //存在这个老人,更新(这里id需要设置)
            elder.setId(DbElder.getId());
            elderMapper.updateById(elder);
        }
        return elder;
    }

    /**
     * 更新床位状态为已入住
     * @param checkInApplyDto
     */
    private Bed updateBedStatus(CheckInApplyDto checkInApplyDto) {
        //1.获得床位id
        Long bedId = checkInApplyDto.getCheckInConfigDto().getBedId();
        //2.更新床位状态
        Bed bed = new Bed();
        bed.setId(bedId);
        bed.setBedStatus(1);
        LambdaQueryWrapper<Bed> bedWrapper = new LambdaQueryWrapper<>();
        bedWrapper.eq(Bed::getId,bedId)
                .eq(Bed::getBedStatus,0);
        int row = bedMapper.update(bed, bedWrapper);
        if(row <= 0){
            throw new BaseException("入住申请,更新床位状态失败");
        }
        return bedMapper.selectById(bedId);
    }

    /**
     * 检验老人是否入住
     * @param checkInApplyDto
     * @return
     */
    private boolean checkElderIsCheckIn(CheckInApplyDto checkInApplyDto) {
        //1.获取老人身份证号码
        String idCardNo = checkInApplyDto.getCheckInElderDto().getIdCardNo();
        LambdaQueryWrapper<Elder> elderWrapper = new LambdaQueryWrapper<>();
        elderWrapper.eq(Elder::getIdCardNo,idCardNo)
                        .in(Elder::getStatus,1,2,4);
        //2.查询老人
        Elder elder = elderMapper.selectOne(elderWrapper);
        if(!ObjUtil.isNull(elder)){
            //2.1查到 返回true
            return true;
        }
        return false;
    }
}
